'use strict';

const { Model, DataTypes } = require('sequelize');
const bcrypt = require('bcrypt');

/**
 * 用户模型定义
 * @param {import('sequelize').Sequelize} sequelize Sequelize实例
 */
module.exports = (sequelize) => {
  class User extends Model {
    static associate(models) {
      // 定义关联
      User.hasMany(models.WhatsappSession, { foreignKey: 'userId' });
      User.hasMany(models.ActivityLog, { foreignKey: 'userId' });
      User.hasMany(models.Message, { foreignKey: 'userId' });
      User.hasMany(models.PresetFile, { foreignKey: 'createdBy' });
      User.hasMany(models.CrmCustomer, { foreignKey: 'createdBy' });
      User.belongsTo(User, { foreignKey: 'createdBy', as: 'Creator' });
    }
    
    // 验证密码
    async verifyPassword(password) {
      return await bcrypt.compare(password, this.password);
    }
  }
  
  const UserModel = sequelize.define('User', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    username: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
      validate: {
        notEmpty: true
      }
    },
    password: {
      type: DataTypes.STRING(100),
      allowNull: false
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    fullName: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: true,
      validate: {
        isEmail: true
      }
    },
    phone: {
      type: DataTypes.STRING(20),
      allowNull: true
    },
    role: {
      type: DataTypes.ENUM('admin', 'sales'),
      defaultValue: 'sales',
      allowNull: false
    },
    department: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('active', 'disabled'),
      defaultValue: 'active',
      allowNull: false
    },
    whatsappId: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: '关联的WhatsApp账号ID'
    },
    whatsappStatus: {
      type: DataTypes.ENUM('disconnected', 'connecting', 'connected'),
      defaultValue: 'disconnected',
      allowNull: false
    },
    lastLoginAt: {
      type: DataTypes.DATE,
      allowNull: true
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false
    }
  }, {
    tableName: 'users',
    timestamps: true,
    indexes: [
      {
        unique: true,
        fields: ['username']
      }
    ],
    hooks: {
      beforeCreate: async (user) => {
        if (user.password) {
          user.password = await bcrypt.hash(user.password, 10);
        }
        // 如果name字段为空，自动设置为fullName或username
        if (!user.name) {
          user.name = user.fullName || user.username;
        }
      },
      beforeUpdate: async (user) => {
        if (user.changed('password')) {
          user.password = await bcrypt.hash(user.password, 10);
        }
        // 如果name字段为空，自动设置为fullName或username
        if (!user.name && (user.changed('fullName') || user.changed('username'))) {
          user.name = user.fullName || user.username;
        }
      }
    }
  });
  
  // 实例方法 - 验证密码
  UserModel.prototype.verifyPassword = async function(password) {
    return bcrypt.compare(password, this.password);
  };

  return UserModel;
}; 